<template>
	<div class="user-profile">
		<van-nav-bar left-arrow @click-left="$router.back()" title="个人信息">
		</van-nav-bar>

		<input @change="onFileChange" type="file" ref="file" hidden>

		<van-cell @click="$refs.file.click()" title="头像" is-link>
			<van-image class="avatar" round fit="cover" :src="$store.state.userPhoto" />
		</van-cell>
		<van-cell @click="isUpdateNameShow = true" title="昵称" is-link :value="user.name"></van-cell>
		<van-cell @click="isUpdateGenderShow = true" title="性别" is-link :value="user.gender === 0 ? '男':'女'"></van-cell>
		<van-cell @click="isUpdateBirthdayShow = true" title="生日" is-link :value="user.birthday"></van-cell>

		<van-popup v-model="isUpdatePhotoShow" position="bottom" style="height: 100%;">
			<updatePhoto v-if="isUpdatePhotoShow" :img="img" @close='isUpdatePhotoShow = false'></updatePhoto>
		</van-popup>

		<van-popup v-model="isUpdateNameShow" position="bottom" style="height: 100%;">
			<UpdateName v-if="isUpdateNameShow" v-model="user.name" @close="isUpdateNameShow = false"></UpdateName>
		</van-popup>

		<van-popup v-model="isUpdateGenderShow" position="bottom">
			<UpdateGender v-if="isUpdateGenderShow" v-model="user.gender" @close="isUpdateGenderShow = false">
			</UpdateGender>
		</van-popup>

		<van-popup v-model="isUpdateBirthdayShow" position="bottom">
			<updateBirthday v-if="isUpdateBirthdayShow" v-model="user.birthday" @close="isUpdateBirthdayShow = false">
			</updateBirthday>
		</van-popup>

	</div>
</template>

<script>
	import {
		getUserProfile
	} from '@/api/user.js'
	import UpdateName from './components/update-name.vue'
	import UpdateGender from './components/update-gender.vue'
	import updateBirthday from './components/update-birthday.vue'
	import updatePhoto from './components/update-photo.vue'


	export default {
		name: 'UserEdit',
		
		components: {
			UpdateName,
			UpdateGender,
			updateBirthday,
			updatePhoto
		},

		data() {
			return {
				user: {},
				isUpdateNameShow: false,
				isUpdateGenderShow: false,
				isUpdateBirthdayShow: false,
				isUpdatePhotoShow: false,
				img: null
			}
		},

		created() {
			this.loadUserProfile()
		},

		methods: {
			async loadUserProfile() {
				try {
					const {
						data: res
					} = await getUserProfile()
					this.user = res.data
				} catch (e) {
					this.$toast("数据获取失败")
				}
			},

			onFileChange() {
				const file = this.$refs.file.files[0]
				this.img = window.URL.createObjectURL(file)
				this.isUpdatePhotoShow = true
				this.$refs.file.value = ''
			},
		},
	}
</script>

<style lang="less" scoped>
	.user-profile {
		.avatar {
			width: 60px;
			height: 60px;
		}
	}

	.van-popup {
		background-color: #f5f7f9;
	}
</style>
